package com.example.springboot.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.CompanyMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.example.springboot.service.ICompanyService;
import com.example.springboot.entity.Company;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小申
 * @since 2023-12-21
 */
@RestController
@RequestMapping("//company")
public class CompanyController {
    
    @Resource
    private ICompanyService companyService;

    @Resource
    private CompanyMapper companyMapper;

    @PostMapping("/sign")
    public Result sign(@RequestBody Company company){
        QueryWrapper<Company> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",company.getName());
        Company register=companyService.getOne(queryWrapper);
        if(register!=null){
            return Result.error(String.valueOf(400),"公司名已存在");
        }

        companyMapper.insert(company);
        return Result.success(company.getId());
    }

    @PostMapping("/login")
    public Result login(@RequestBody Company company){
        QueryWrapper<Company> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",company.getName());
        queryWrapper.eq("password",company.getPassword());
        queryWrapper.eq("phone",company.getPhone());
        Company login=companyService.getOne(queryWrapper);

        if(login.getPassword().equals(company.getPassword())){
            return Result.success(login);
        }
        return Result.error("400","账号或密码或手机错误");
    }

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Company company){
        return Result.success(companyService.saveOrUpdate(company));
    }

    //删除单条数据
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        return Result.success(companyService.removeById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(companyService.removeByIds(ids));
    }

    //获取全部数据
    @GetMapping
    public Result findAll(){
        return Result.success(companyService.list());
    }

    //获取单条数据
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id){
        return Result.success(companyService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize){
        QueryWrapper<Company> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(companyService.page(new Page<>(pageNum,pageSize),queryWrapper));
    }
}

